package com.crawler.utils

import java.io.{PrintWriter, File}
import java.util.Calendar

import com.crawler.comm.CrawlerConfig
import com.crawler.proxy.CrawlProxy
import com.typesafe.config.ConfigFactory
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.util.Zip4jConstants
import net.lingala.zip4j.core.ZipFile

import scala.io.Source

/**
  * Created by tongtao.zhu on 2017/2/21.
  */
object ZipUtils {
  val config = ConfigFactory.load()
  val crawlerConfig = new CrawlerConfig(config)

  def createZipFile(path: String,password:String,userName:String,ip:String,port:String): String ={
    val milliseconds = Calendar.getInstance().getTime.getTime
    val proxyPath = path+"proxy_"+milliseconds+".zip"
    val zipFile = new ZipFile(proxyPath)
    val parameters =  new ZipParameters()
    parameters.setCompressionLevel(Zip4jConstants.COMP_DEFLATE)
    parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL)
    val content = readFile(path+"background.js").replace("%proxy_host",ip).replace("%proxy_port",port).replace("%username",userName).replace("%password",password)
    val file =writeFile(crawlerConfig.proxyExtensionDir,"background","js",content)
    val manifestFile = new File(path+"manifest.json")
    zipFile.addFile(file,parameters)
    zipFile.addFile(manifestFile,parameters)
    proxyPath
  }

  def changeProxyFile(proxyPath:String,path:String,crawlProxy: CrawlProxy): Unit ={
    val zipFile = new ZipFile(proxyPath)
    val parameters =  new ZipParameters()
    parameters.setCompressionLevel(Zip4jConstants.COMP_DEFLATE)
    parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL)
    val content = readFile(path+"background.js").replace("%proxy_host",crawlProxy.ip).replace("%proxy_port",crawlProxy.port.toString).replace("%username",crawlProxy.user).replace("%password",crawlProxy.password)
    val file =writeFile(crawlerConfig.proxyExtensionDir,"background","js",content)
    val manifestFile = new File(path+"manifest.json")
    zipFile.addFile(file,parameters)
    zipFile.addFile(manifestFile,parameters)
  }

  def readFile(path:String): String ={
    val content = Source.fromFile(new File(path)).mkString
    content
  }

  def writeFile(path:String,suffix:String, prefix:String,content:String): File ={
    val file = new File(path+suffix+"."+prefix)
    if (!file.exists()){
      file.createNewFile()
    }
    val pw = new PrintWriter(file)
    pw.append(content)
    pw.flush()
    pw.close()
    file
  }

  def main(args: Array[String]) {
    val proxyPath = createZipFile("D:\\chrome\\Selenium-Chrome-HTTP-Private-Proxy-master\\","dpadsl","dpadsl2017","117.82.227.58","8888")
    println(proxyPath)
  }
}
